package com.daydayup.learn;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadLocalStatic {

    public static ExecutorService threadPool = Executors.newFixedThreadPool(16);
    static SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    static ConcurrentHashMap<String,Integer> map = new ConcurrentHashMap<>();

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++) {
            int finalI = i;
            threadPool.submit(() -> {
                String s = new ThreadLocalStatic().date(finalI);
                if (map.containsKey(s)) {
                    map.put(s, map.get(s) + 1);
                } else {
                    map.put(s, 1);
                }
                System.out.println(s);
            });
        }
        threadPool.shutdown();

        while (true) {
            if (threadPool.isTerminated()){
                for (Map.Entry<String, Integer> entry : map.entrySet()) {
                    if (entry.getValue() > 1) {
                        System.out.println(entry.getKey() + " -> " + entry.getValue());
                    }
                }
                break;
            }
            TimeUnit.SECONDS.sleep(1);
        }
    }

    public String date(int seconds) {
        Date date = new Date(1000L * seconds);
        SimpleDateFormat df = ThreadSafeFormatter.dateFormatThreadLocal.get();
        return df.format(date);
    }
}

class ThreadSafeFormatter {
    public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = ThreadLocal.withInitial(() -> ThreadLocalStatic.dateFormat);
}
